<?php
declare (strict_types = 1);

namespace app\controller;


use Overtrue\Socialite\SocialiteManager;
use think\facade\Session;

class Authorize extends Common
{
    protected $config = [];
    public function __construct()
    {
        $this->config = [
            'qq' => [
                'client_id'     => '101880041',
                'client_secret' => 'e4757d436b8eb11bb76c93cd71b21399',
                'redirect'      => request()->domain().'/Authorize/qq_callback',
            ],
        ];
        parent::__construct();
    }
    public function qq()
    {


        $socialite = new SocialiteManager($this->config);
        $response = $socialite->driver('qq')->redirect();
        return $response->send();// or $response->send();
    }

    public function qq_callback()
    {
        $socialite = new SocialiteManager($this->config);
        $user = $socialite->driver('qq')->user();


        $user->getId();        // 1472352

        $data['nickname'] = $user->getNickname();
        $data['headimgurl'] = $user->getAvatar();
        $data['openid_qq'] =  $user->getId();
        $data['email'] =  $user->getEmail();
        $data['provider'] =  $user->getProviderName();
        $data['reg_time'] =  time();
        $data['last_time'] =  time();
        $data['sign_time'] =  1;
        $data['reg_ip'] =  request()->ip();
        $data['login_count'] =  1;

        $res = \app\common\model\User::where("openid_qq",$data["openid_qq"])
            ->find();
        $token = jwt_encode($user);
        if(!$res){
            $t  = \app\common\model\User::create($data);
            $res =$t;
        }


        Session::set("index_user",$res);
        $url = url("Index/index",["token"=>$token]);
        return redirect((string)$url);


        //$user->getUsername();  // "overtrue"
        //$user->getName();      // "安正超"
        //$user->getEmail();     // "anzhengchao@gmail.com"
        //$user->getProviderName(); // GitHub
    }
}
